package com.teacold.customdemo.chapter_eight;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class PorterDuffXfermodeView extends View {
    private int width=200;
    private int height=200;
    private Bitmap dstBmp;
    private Bitmap srcBmp;
    private Paint mPaint;

    public PorterDuffXfermodeView(Context context) {
        this(context,null);
    }

    public PorterDuffXfermodeView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PorterDuffXfermodeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setLayerType(LAYER_TYPE_SOFTWARE,null);
        dstBmp=makeDst(width,height);
        srcBmp=makeSrc(width,height);
        mPaint=new Paint();
    }

    private Bitmap makeSrc(int width, int height) {
        Bitmap bitmap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bitmap);
        Paint mPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(0xFF66AAFF);
        canvas.drawRect(0,0,width,height,mPaint);
        return bitmap;

    }

    private Bitmap makeDst(int width, int height) {
        Bitmap bm=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bm);
        Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(0xffffcc44);
        canvas.drawOval(new RectF(0,0,width,height),paint);
        return bm;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int layoutId=canvas.saveLayer(0,0,getWidth(),getHeight(),null,Canvas.ALL_SAVE_FLAG);
        canvas.drawBitmap(dstBmp,0,0,mPaint);
//        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
        canvas.drawBitmap(srcBmp,width/2,height/2,mPaint);
        mPaint.setXfermode(null);
        canvas.restoreToCount(layoutId);

    }
}
